<?php 

class LsActiveDataProvider
extends CActiveDataProvider
{
	
	/**
	 * 
	 * @var ModuleCache
	 */
	protected $_cache;
	
	/**
	 * 
	 * @var array
	 */
	protected $_cacheTags = array();
	
	
	public $cacheTime = 43200;
	public $useCache = false;
	
	
	/**
	 * Constructor.
	 * @param mixed $modelClass the model class (e.g. 'Post') or the model finder instance
	 * (e.g. <code>Post::model()</code>, <code>Post::model()->published()</code>).
	 * @param array $config configuration (name=>value) to be applied as the initial property values of this class.
	 */
	public function __construct($modelClass,$config=array()){
		parent::__construct($modelClass,$config);
		$this->_cache = array_shift(Yii::E()->GetModule('Cache_x'));
	}
	
	/**
	 * @return Entity[]
	 */
	public function getEdata($refresh=false){
		if(!$this->useCache){
			return $this->getEdataNoCache($refresh);
		}
		
		$cacheKey = $this->getCacheKey();
		$noCache = false;
		
		if($refresh){
			$noCache = true;
		}
		
		if($noCache || ($data = $this->_cache->Get($cacheKey)) === false){
			$data = $this->getEdataNoCache($refresh);
			if($data && $data[array_shift(array_keys($data))] instanceof Entity){
				$this->_cache->Set($data,$cacheKey,$this->getCacheTags(),$this->cacheTime);
			}
		}
		
		return $data;
	}
	
	public function getEdataNoCache($refresh=false){
		$ars = $this->getData($refresh);
		$es = array();
		foreach($ars as $i => $ar){
			$es[$i] = $ar->canGetProperty('entity')
				? $ar->getEntity()
				: $ar
			;
		}
		return $es;
	}
	
	
	public function getCacheKey($count=false){
		
		$criteria=clone $this->getCriteria();
		
		if(!$count){
			if(($pagination=$this->getPagination())!==false)
			{
				$pagination->setItemCount($this->getTotalItemCount());
				$pagination->applyLimit($criteria);
			}
	
			if(($sort=$this->getSort())!==false)
				$sort->applyOrder($criteria);
		}
		
		return $this->modelClass.'_'
			.serialize($criteria->toArray())
			.($count ? '_count' : '_data')
		;
	}
	
	public function getCacheTags(){
		return $this->_cacheTags;
	}
	
	public function setCacheTags($tags,$clear=false){
		if($clear){
			$this->_cacheTags = array();
		}
		if(is_null($tags)){
			return;
		}
		$tags = is_array($tags) ? $tags : array($tags);
		$this->_cacheTags = array_merge($this->_cacheTags, $tags);
	}
	
	
	/**
	 * Calculates the total number of data items.
	 * @return integer the total number of data items.
	 */
	protected function calculateTotalItemCount(){
		if(!$this->useCache){
			return parent::calculateTotalItemCount();
		}
		$cacheKey = $this->getCacheKey(true);
		if(($data = $this->_cache->Get($cacheKey)) === false){
			$data = parent::calculateTotalItemCount();
			$this->_cache->Set($data,$cacheKey,$this->getCacheTags(),$this->cacheTime);
		}
		return $data;
	}
	
}

?>